package cn.frh.service.impl;

import cn.frh.Exception.GlobalCustomException;
import cn.frh.Exception.GlobalExceptionCode;
import cn.frh.domain.Product;
import cn.frh.domain.PurchaseApply;
import cn.frh.domain.Stock;
import cn.frh.domain.StockWarningLog;
import cn.frh.dto.StockDto;
import cn.frh.feign.ProductService;
import cn.frh.feign.PurchaseService;
import cn.frh.mapper.StockMapper;
import cn.frh.properties.StockThresholdProperties;
import cn.frh.result.JSONResult;
import cn.frh.service.IStockService;
import cn.frh.service.IStockWarningLogService;
import cn.frh.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tom
 * @since 2022-09-29
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {


    @Autowired
    private ProductService productService;
    @Autowired
    private StockThresholdProperties stockThresholdProperties;

    @Autowired
    private IStockWarningLogService stockWarningLogService;

    @Autowired
    private PurchaseService purchaseService;

    @Override
    public void inaout(StockDto stockDto) {
        //1.判断出入库 0入1出
        Stock stock = selectStock(stockDto.getProductId());
        if (stockDto.getStatus() == 0){
            //如果是入库 判断库里面有没有这个商品
            Long productId = stockDto.getProductId();
            //库里面的商品信息
            stock = selectById(productId);
            if (stock== null){
                //如果商品表等于空 直接抛出异常
                //商品表信息
                JSONResult jsonProduct = productService.get(stockDto.getProductId());
                Object data = jsonProduct.getData();
                AssertUtil.isNotNull(data,GlobalExceptionCode.PARAM_IS_NULL_ERROR);
                //如果商品表里有
                Product product = JSON.parseObject(JSON.toJSONString(data), Product.class);
                Stock stock1 = new Stock();
                stock1.setProductId(product.getId());
                stock1.setCount(stockDto.getCount());
                stock1.setCreateTime(new Date());
                stock1.setProductName(product.getProductName());
                stock1.setTypeId(product.getTypeId());
                insert(stock1);
            }else {
                //如果库里有
                //如果不等于空就直接入库
                stock.setCount(stock.getCount() + stockDto.getCount());
                updateById(stock);
            }
        }else {
            // 出库 判断出库数量是否小于阈值
            Integer count = stock.getCount();
            if (stockDto.getCount() < count){
                //如果小于阈值 就说明需要报警
                if(count < stockThresholdProperties.getThreshold()){
                    Date date = new Date();
                    //添加警告日志
                    StockWarningLog warningLog = new StockWarningLog();
                    BeanUtils.copyProperties(stock, warningLog);
                    warningLog.setInfo(stock.getProductName() + "库存不足了，请及时采购！");
                    warningLog.setCreateTime(date);
                    stockWarningLogService.insert(warningLog);
                    PurchaseApply purchaseApply = new PurchaseApply();
                    BeanUtils.copyProperties(stock, purchaseApply);
                    purchaseApply.setCreateTime(date);
                    purchaseApply.setCount(100);
                    purchaseApply.setStatus(0);
                    purchaseService.saveOrUpdate(purchaseApply);
                    throw new GlobalCustomException("库存不足，出库失败！");
                }
            }else {
                //库存充足
                stock.setCount(stock.getCount() - stockDto.getCount());
                updateById(stock);
            }

        }
    }

    @Override
    public List<Stock> lack() {
        Integer threshold = stockThresholdProperties.getThreshold();
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.lt("count", threshold);
        List<Stock> stocks = selectList(wrapper);
        return stocks;
    }

    private Stock selectStock(Long productId) {
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.eq("product_id", productId);
        return selectOne(wrapper);
    }

}
